package cc.linker.steplink.crm.merchanth5.controller.acs;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.pojo.CheckMerchantOrderPo;
import cc.linker.steplink.crm.merchanth5.pojo.ShoppingCartGoodsPo;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.integral.IntegralH5Service;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 新支付流程
 * @Author: wuyue
 * @Date: 2019/9/20 13:22
 * @Version: v1.9.1
 */
@Slf4j
@RestController
public class PurchaseProcessController {

    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private MallService mallService;
    @Autowired
    private RequestFilter requestFilter;
    @Autowired
    private IntegralH5Service integralH5Service;


    /**
     * 获取订单支付状态
     * @param orderSn
     * @return
     */
    @GetMapping("/h5/acs/getorderpaysta")
    public Map<String,Object> getOrderPayStatus(String orderSn,String payType){
        return purchaseProcessService.getOrderPayStatus(orderSn,payType);
    }


    /**
     * 确认订单
     *
     * @param shoppingCartIds
     * @param goodsId
     * @param skuId
     * @param buyCount
     */
    @PostMapping("/h5/acs/checkorder")
    public Map<String,Object> checkOrder(@RequestBody Map<String, Object> param, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        param.put("customerId", customerId);
        String orgId = wxUser.getOrgId();
        param.put("orgId", orgId);
        param.put("isVip",wxUser.getIsVip());
        Map<String,Object> data = new HashMap<>();
        CouponCustomerInfo couponCustomerInfo = requestFilter.getCouponCustomerInfo(request);
        List<CheckMerchantOrderPo> checkMerchantOrderPos = purchaseProcessService.checkOrderNew(param,couponCustomerInfo);
        long totalMoneyTemp = 0L;
        long totalMoney = 0L;
        int totalNum = 0;
        int scoreAble = 0;
        int score = 0;
        long discount = 0L;
        for (CheckMerchantOrderPo da : checkMerchantOrderPos) {
            totalMoney = totalMoney + da.getOrderTotalPriceTemp();
            totalNum = totalNum + da.getGoodsNum();
            totalMoneyTemp = totalMoneyTemp + da.getOrderTotalPriceTemp();
            scoreAble = scoreAble + da.getScoreAble();
            score = da.getScore();
            discount = discount + da.getDiscountCent();
        }
        data.put("totalNum",totalNum);
        data.put("totalMoney",NumberUtils.fenToYuan(totalMoneyTemp));
        data.put("orderList",checkMerchantOrderPos);
        data.put("scoreAble",scoreAble);
        data.put("score",score);
        data.put("discount",NumberUtils.fenToYuan(discount));
        return data;
    }

    /**
     * 确认知识付费订单
     *
     * @param goodsId
     */
    @PostMapping("/h5/knowledge/checkorder")
    public Map<String, Object> checkKnowledgeOrder(@RequestBody Map<String, Object> param, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        param.put("customerId", customerId);
        String orgId = wxUser.getOrgId();
        param.put("orgId", orgId);
        return purchaseProcessService.checkKnowledgeOrder(param);
    }

    /**
     * 创建订单
     *
     * @param addressId       地址id
     * @param goodsId         商品id(分小b商品和大b商品)
     * @param goodsNum        商品数量
     * @param skuId           skuId
     * @param shoppingCartIds 购物车id
     * @param orderSn         订单sn
     * @param distributor     分享人id
     * @param score           是否使用积分(0-不使用，1-使用)(使用即为全部使用，但不超过订单价格)
     * @param remark          备注
     * @param type            类型1-要分润(给购买者和分享人建立上下级关系)0-不分
     * @param articleId       文章id(从文章购买的需求)
     * @param linkId          分享链路Id
     * @param couponId         优惠券Id
     */
    @PostMapping("/h5/acs/createorder")
    public Map createOrder(@RequestBody Map<String, Object> param, HttpServletRequest request) throws GlobalException, UnsupportedEncodingException {
        LOGGER.info("下单参数===[{}]", param);
        // 创建订单，生成返润体系，然后调中金得到支付签名，返回给前端
        WxUser wxUser = requestFilter.getWxUser(request);
        param.put("customerId", wxUser.getCustomerId());
        param.put("orgId", wxUser.getOrgId());
        param.put("openid", wxUser.getPayOpenId());
        param.put("payMode", wxUser.getPayMode());
        param.put("nickName", wxUser.getNickname());
        param.put("isVip", "1".equals(wxUser.getIsVip().toString()));
        //WxUser wxUser =  requestFilter.getWxUser(request);
        String orderSn = "";
        if(!StringUtils.isEmpty(param.get("orderSn"))){
            orderSn = param.get("orderSn").toString();
            if(orderSn.startsWith("I")){
                return integralH5Service.createOrder(param);
            }
        }
        CouponCustomerInfo couponCustomerInfo = requestFilter.getCouponCustomerInfo(request);
        param.put("couponCustomerInfo", couponCustomerInfo);
        return purchaseProcessService.createOrder(param);
    }

    /**
     * 在小程序中获取签名
     *
     * @param ：orderSn 订单sn
     */
    @PostMapping("/h5/acs/payOrderByxcx")
    public Map payOrderByxcx(@RequestBody Map<String, Object> param) throws GlobalException, UnsupportedEncodingException {
        if (StringUtils.isEmpty(param.get("orderSn")) || StringUtils.isEmpty(param.get("openId"))) {
            throw GlobalException.build("参数错误");
        }else {
            param.put("openid",param.get("openId"));
        }
        String orderSn = param.get("orderSn").toString();
        if (orderSn.startsWith("I")){
            String openid = param.get("openId").toString();
            //积分商城
            return integralH5Service.payOrderByxcx(orderSn,openid);
        }
        // 根据订单查出对应的数据，然后调中金得到支付签名，返回给前端
        return purchaseProcessService.payOrderByxcx(param);
    }

    /**
     * 订单回调
     *
     * @param orderSn 订单sn
     * @param status  状态//10处理中，20成功；30失败；40交易关闭；50未支付
     */
    @PostMapping("/acs/paycallback")
    public void payCallback(@RequestBody Map<String, Object> param) throws Exception {
        if(param!=null){
            LOGGER.info("回调请求参数===msg===[{}]",param);
        }else {
            LOGGER.info("回调请求参数为空");
        }

        if (!param.containsKey("orderSn") || !param.containsKey("status")) {
            throw GlobalException.build("缺少参数");
        }
        // 回调
        purchaseProcessService.payCallback(param);
    }

    /**
     * 微信回调
     */
    @PostMapping("/acs/paycallbackforwx")
    public void payCallBackForWx(@RequestBody Map<String, Object> param) throws Exception {
        purchaseProcessService.payCallBackForWx(param);
    }

    /**
     * 通联退款回调
     */
    @PostMapping("/acs/refundcallback")
    public void refundCallBack(@RequestBody Map<String, Object> param) throws Exception {
        purchaseProcessService.refundCallBack(param);
    }

    @PostMapping("/acs/transferRefundCallBack")
    public void transferRefundCallBack(@RequestBody Map<String, Object> param) throws Exception {
        purchaseProcessService.transferRefundCallBack(param);
    }

    /**
     * 用户openid+token查customerId
     */
    @PostMapping("/h5/getCustomerId")
    public Map<String, Object> getCustomerId(@RequestBody Map<String, Object> param) {
        String orgId = purchaseProcessService.getOrgIdByToken(param);
        //String customerId = purchaseProcessService.getCustomerIdByTokenAndOpenid(param);
        param.put("orgId",orgId);
        String customerId = purchaseProcessService.getCustomerIdByOrgIdAndOpenid(param);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        return map;
    }

    /**
     * 给某机构下用户开户
     */
    @GetMapping("/openAccounts")
    public void openAccounts(String orgId) {
        purchaseProcessService.openAccountsByOrgId(orgId);
    }
}
